from django.shortcuts import render, redirect, get_object_or_404
from .models import Test, Task, Competitions
from .forms import TestForm, TaskFormSet
from django.contrib.auth.decorators import login_required
from django.utils.timezone import now

def competitions(request):
    competitions = Competitions.objects.all()
    return render(request, 'competitions/competitions.html', {'competitions': competitions})

@login_required
def create_test(request):
    if request.method == 'POST':
        form = TestForm(request.POST)
        formset = TaskFormSet(request.POST, request.FILES)
        if form.is_valid() and formset.is_valid():
            test = form.save(commit=False)
            test.author = request.user  # Убедитесь, что поле author существует в модели Test
            test.save()
            formset.instance = test
            formset.save()
            return redirect('test_detail', test_id=test.id)
        else:
            print(form.errors)
            print(formset.errors)
    else:
        form = TestForm()
        formset = TaskFormSet()

    return render(request, 'competitions/create_test.html', {'form': form, 'formset': formset})

def test_detail(request, test_id):
    test = get_object_or_404(Test, id=test_id)
    return render(request, 'competitions/test_detail.html', {'test': test})
